package com.library.bookmanagement.util;

import com.library.bookmanagement.entity.*;
import com.library.bookmanagement.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author ：ZXM
 * @date ：Created in 2020/5/30 14:55
 * @description：定时任务设置类
 */
@Component
public class Scheduler {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
    private ReadMapper readMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private ReserveMapper reserveMapper;
    @Autowired
    private OverdueMapper overdueMapper;

    @Value("${spring.mail.username}")
    private String from;
    // 注入邮件处理Bean
    @Autowired
    private JavaMailSender javaMailSender;

    /**
    * @Description: 实现借阅记录的提醒,每天上午10：30执行该定时方法，提醒剩余7天之内还未还书的读者
    * @Param: []
    * @return: void
    * @Author: ZXM
    * @Date: 2020/6/10
    */
    @Scheduled(cron = "0 30 10 ? * *")
    public void BorrowInfoMail(){
        Date date = new Date(System.currentTimeMillis());
        Date  threeDate= new Date(System.currentTimeMillis() + 604800000L);
        List<Read> reads = readMapper.selectByScheduled(date, threeDate);
        if(reads.size() != 0){
            for (Read read:reads) {
                User user = userMapper.selectByPrimaryKey(read.getUserId());
                Book book = bookMapper.selectByPrimaryKey(read.getBookId());
                String email = user.getuEmail();
                String message = "亲爱的"+user.getuName()+"，您好！"+'\n'
                        +"您于"+dateFormat.format(read.getLendTime())+"借阅的《"+book.getbName()+"》即将到期，请在"+dateFormat.format(read.getBackTime())+"前归还!";
                sendEmail(email,message,Constant.MESSAGE_SCHEDULED_BORROW);
            }
        }
    }

    /**
    * @Description:实现预定时间提醒
    * @Param: []
    * @return: void
    * @Author: ZXM
    * @Date: 2020/6/10
    */
    @Scheduled(cron = "0 0 9 ? * *")
    public void ReserveEmail(){
        Date date = new Date(System.currentTimeMillis());
        // 提前2天时间提醒
        Date  twoDate= new Date(System.currentTimeMillis() + 172800000L);
        List<Reserve> reserves = reserveMapper.selectByScheduled(date, twoDate);
        if(reserves != null){
            for (Reserve reserve:reserves){
                User user = userMapper.selectByPrimaryKey(reserve.getUserId());
                Book book = bookMapper.selectByPrimaryKey(reserve.getBookId());
                String email = user.getuEmail();
                String message = "亲爱的"+user.getuName()+"，您好！"+'\n'
                        +"您于"+dateFormat.format(reserve.getStartTime())+"预定的《"+book.getbName()+"》即将到期，请于"+dateFormat.format(reserve.getLastTime()
                )+"之前登录官网选择延迟预定!系统将自动清理预定信息";
                sendEmail(email,message,Constant.MESSAGE_SCHEDULED_RESERVE);
            }
        }
    }

    /**
    * @Description:每天晚上更新预定数据表，删除一些过时预定
    * @Param: []
    * @return: void
    * @Author: ZXM
    * @Date: 2020/6/10
    */
    @Scheduled(cron = "0 0 0 ? * *")
    public void UpdateReserve(){
        Date date = new Date(System.currentTimeMillis());
        reserveMapper.deleteByScheduled(date);
    }

    /**
    * @Description: 可预订状态提示,每次提醒一名用户,每天9点跟新一次
    * @Param: []
    * @return: void
    * @Author: ZXM
    * @Date: 2020/6/10
    */
    @Scheduled(cron = "0 30 9 ? * *")
    public void ReserveRemindEmail(){
        List<Integer> integers = reserveMapper.selectAllBookId();
        if(integers.size() != 0){
            for(Integer bookId:integers){
                Book book = bookMapper.selectByPrimaryKey(bookId);
                Integer bookCount = book.getbCount();
                if(bookCount > 0){
                    List<Integer> userIds = reserveMapper.selectByAllUserId(book.getbId());
                    if(userIds.size() != 0){
                        int index = 0;
                        for (Integer userId:userIds) {
                            User user = userMapper.selectByPrimaryKey(userId);
                            String email = user.getuEmail();
                            String message = "亲爱的"+user.getuName()+"，您好！"+'\n'
                                    +"您预定的《"+book.getbName()+"》已有库存，请及时前往图书室完成借阅!";
                            sendEmail(email,message,Constant.MESSAGE_SCHEDULED_RESERVE);
                            index+=1;
                            if(index == bookCount){
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

    /**
    * @Description: 每五秒执行逾期记录修改功能
    * @Param: []
    * @return: void
    * @Author: ZXM
    * @Date: 2020/6/19
    */
    @Scheduled(cron = "0/5 * * * * ? ")
    public void editOverDue(){
        Date date = new Date(System.currentTimeMillis());
        List<Read> reads = readMapper.selectByDate(date);
        if(reads != null){
            for(Read read:reads){
                User user = userMapper.selectByPrimaryKey(read.getUserId());
                user.setOverNumber(user.getOverNumber()+1);
                if(user.getOverNumber() >= 3){
                    user.setuBoolean(1);
                }
                userMapper.updateByPrimaryKeySelective(user);
                Overdue overdue = new Overdue();
                overdue.setUserId(read.getUserId());
                overdue.setBookId(read.getBookId());
                overdue.setStartTime(read.getBackTime());
                ReaderKey readKey = new ReaderKey();
                readKey.setUserId(read.getUserId());
                readKey.setBookId(read.getBookId());
                readMapper.deleteByPrimaryKey(readKey);
                overdueMapper.insertSelective(overdue);
            }
        }
    }
    /**
    * @Description: 发送邮件的方法
    * @Param: [email, message, subject]
    * @return: void
    * @Author: ZXM
    * @Date: 2020/6/10
    */
    private void sendEmail(String email,String message,String subject){
    // 创建单邮件对象并设置邮件内容
    SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
    simpleMailMessage.setFrom(from);
    simpleMailMessage.setTo(email);
    simpleMailMessage.setSubject(Constant.MEASSAGE_REGISTER_TITLE);
    simpleMailMessage.setText(message);
    // 发送邮件
    javaMailSender.send(simpleMailMessage);
}
}
